package com.myCommon.security.entity;

import com.alibaba.fastjson.annotation.JSONField;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class LoginUser implements UserDetails {
      
      private User user;
      @JSONField(serialize = false)
      private List<String> userAuthList;
      private List<SimpleGrantedAuthority> authorities;
      
      public LoginUser(User user, List<String> userAuthList) {
            this.user = user;
            this.userAuthList = userAuthList;
      }
      
      @Override
      public Collection<? extends GrantedAuthority> getAuthorities() {
            if (!CollectionUtils.isEmpty(authorities)) {
                  return authorities;
            }
      
            authorities = userAuthList.stream()
                  .map(SimpleGrantedAuthority::new)
                  .collect(Collectors.toList());
      
      
            return authorities;
      }
      
      @Override
      public String getPassword() {
            return user.getPassword();
      }
      
      @Override
      public String getUsername() {
            return user.getUserName();
      }
      
      @Override
      public boolean isAccountNonExpired() {
            return true;
      }
      
      @Override
      public boolean isAccountNonLocked() {
            return true;
      }
      
      @Override
      public boolean isCredentialsNonExpired() {
            return true;
      }
      
      @Override
      public boolean isEnabled() {
            return true;
      }
}
